/*
 * tab_setup.cpp
 *
 *  Created on: 15.06.2013
 *      Author: SpirTanol
 */

#include "ui/tab_setup.h"
#include "ui/main_window.h"
#include "ui/time_dialog.h"
#include "events/data_event.h"
#include "packets/config_packet.h"
#include "packets/watch_data_packet.h"
#include "device/device_info.h"
#include "ui/idle_plot_dialog.h"
#include "packets/run_config_packet.h"

// QT
#include <QLabel>
#include <QGridLayout>
#include <QBoxLayout>
#include <QCheckBox>
#include <QComboBox>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QPushButton>
#include <QSpacerItem>
#include <QMessageBox>
#include <QDebug>
//======================================================================================
extern int gDeviceVersion;
//======================================================================================
TabSetup::TabSetup(MainWindow *mainWindow) : oMainWindow(mainWindow)
{
	QGridLayout *l = new QGridLayout(this);

	// Левая колонка
	QGridLayout *leftCol = new QGridLayout();
	l->addLayout(leftCol, 0, 0);

	QGridLayout *leftColOpt = new QGridLayout();
	leftCol->addLayout(leftColOpt, 0, 0);

	int row = 0;

	QLabel *label = new QLabel(trUtf8("Номинальный ток двигателя"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oDSpinNominalCur = new QDoubleSpinBox();
	oDSpinNominalCur->setSuffix(trUtf8("А"));
	leftColOpt->addWidget(oDSpinNominalCur, row++, 1);

	label = new QLabel(trUtf8("Время отключения при двухкратной перегрузке"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oSpinTimeOff = new QSpinBox();
	oSpinTimeOff->setSuffix(trUtf8(" сек"));
	oSpinTimeOff->setRange(10, 200);
	leftColOpt->addWidget(oSpinTimeOff, row++, 1);

	label = new QLabel(trUtf8("Порог срабатывания защиты от перегрузки, кратность тока"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oSpinOverloadCur = new QSpinBox();
	oSpinOverloadCur->setRange(2, 10);
	leftColOpt->addWidget(oSpinOverloadCur, row++, 1);

	label = new QLabel(trUtf8("Время реакции защиты от перегрузки"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oSpinOverloadTime = new QSpinBox();
	oSpinOverloadTime->setRange(1, 999);
	oSpinOverloadTime->setSuffix(trUtf8("0 мсек"));
	leftColOpt->addWidget(oSpinOverloadTime, row++, 1);

	label = new QLabel(trUtf8("Разрешение быстродействующей защиты"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oCheckAllowFastProtect = new QCheckBox();
	oCheckAllowFastProtect->setLayoutDirection(Qt::RightToLeft);
	leftColOpt->addWidget(oCheckAllowFastProtect, row++, 1);

	label = new QLabel(trUtf8("Порог отключения по перекосу токов фаз"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oSpinImbalance = new QSpinBox();
	oSpinImbalance->setSuffix(trUtf8("%"));
	oSpinImbalance->setRange(1, 70);
	leftColOpt->addWidget(oSpinImbalance, row++, 1);

	label = new QLabel(trUtf8("Время срабатывания защиты от перекоса токов"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oSpinTimeProtectOfBiasCurrents = new QSpinBox();
	oSpinTimeProtectOfBiasCurrents->setSuffix(trUtf8("0 мсек"));
	oSpinTimeProtectOfBiasCurrents->setRange(1, 255);
	leftColOpt->addWidget(oSpinTimeProtectOfBiasCurrents, row++, 1);

	label = new QLabel(trUtf8("Допустимое количество оборваных фаз"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oSpinAllowCrashPhase = new QSpinBox();
	oSpinAllowCrashPhase->setRange(0, 3);
	leftColOpt->addWidget(oSpinAllowCrashPhase, row++, 1);

	label = new QLabel(trUtf8("Минимально допустимый ток двигателя"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oSpinAllowCur = new QSpinBox();
	oSpinAllowCur->setSuffix(trUtf8("%"));
	oSpinAllowCur->setRange(1, 60);
	leftColOpt->addWidget(oSpinAllowCur, row++, 1);

	label = new QLabel(trUtf8("Коэффициент коррекции минимально допустимого тока"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);

	QBoxLayout *bl = new QBoxLayout(QBoxLayout::LeftToRight);
	oDSpinProtectionThresholdOfIdle = new QDoubleSpinBox();
	oDSpinProtectionThresholdOfIdle->setDecimals(1);
	oDSpinProtectionThresholdOfIdle->setRange(-2.0, 2.0);
	oDSpinProtectionThresholdOfIdle->setValue(0.0);
	oDSpinProtectionThresholdOfIdle->setSingleStep(0.1);
	bl->addWidget(oDSpinProtectionThresholdOfIdle);
	oBtnShowIdlePlot = new QPushButton(trUtf8("Диаграмма"));
	connect(oBtnShowIdlePlot, SIGNAL(clicked()), this, SLOT(onBtnShowIdlePlot()));
	bl->addWidget(oBtnShowIdlePlot);
	leftColOpt->addLayout(bl, row++, 1);

	label = new QLabel(trUtf8("Допуск на напряжение питающих фаз"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oComboAllowVoltage = new QComboBox();
	oComboAllowVoltage->addItem(trUtf8("Минус 15 + 10%"));
	oComboAllowVoltage->addItem(trUtf8("Минус 20 + 15%"));
	oComboAllowVoltage->addItem(trUtf8("Минус 25 + 20%"));
	oComboAllowVoltage->addItem(trUtf8("Минус 30 + 25%"));
	leftColOpt->addWidget(oComboAllowVoltage, row++, 1);

	label = new QLabel(trUtf8("Проверка последовательности фаз питающей сети"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oCheckTestingPhase = new QCheckBox();
	oCheckTestingPhase->setLayoutDirection(Qt::RightToLeft);
	leftColOpt->addWidget(oCheckTestingPhase, row++, 1);

	label = new QLabel(trUtf8("Выбор порога срабатывания защиты по сопротивлению изоляции"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oComboProtectionThresholdOfInsulation = new QComboBox();
	oComboProtectionThresholdOfInsulation->addItem(trUtf8("0,55МОм"));
	oComboProtectionThresholdOfInsulation->addItem(trUtf8("1,1МОм"));
	oComboProtectionThresholdOfInsulation->setCurrentIndex(1);
	leftColOpt->addWidget(oComboProtectionThresholdOfInsulation, row++, 1);

	label = new QLabel(trUtf8("Разрешение защит по термодатчику РТС"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oCheckAllowTempProtect = new QCheckBox();
	oCheckAllowTempProtect->setLayoutDirection(Qt::RightToLeft);
	leftColOpt->addWidget(oCheckAllowTempProtect, row++, 1);

	label = new QLabel(trUtf8("Разрешение защиты по термодатчику РТ100"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oCheckAllowTempProtect100 = new QCheckBox();
	oCheckAllowTempProtect100->setLayoutDirection(Qt::RightToLeft);
	leftColOpt->addWidget(oCheckAllowTempProtect100, row++, 1);

	label = new QLabel(trUtf8("Порог срабатывания защиты по термодатчику РТ100"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oSpinTresholdTemp100 = new QSpinBox();
	oSpinTresholdTemp100->setSuffix(trUtf8(" °C"));
	oSpinTresholdTemp100->setRange(10, 255);
	leftColOpt->addWidget(oSpinTresholdTemp100, row++, 1);

	label = new QLabel(trUtf8("Разрешение защит по датчику влажности"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	leftColOpt->addWidget(label, row, 0);
	oCheckAllowWetProtect = new QCheckBox();
	oCheckAllowWetProtect->setLayoutDirection(Qt::RightToLeft);
	leftColOpt->addWidget(oCheckAllowWetProtect, row++, 1);

	leftColOpt->addItem(new QSpacerItem(0, 0, QSizePolicy::Preferred, QSizePolicy::Expanding), row++, 0);

	// Правая колонка
	QGridLayout *rightCol = new QGridLayout();
	l->addLayout(rightCol, 0, 1);
	row = 0;

	QGridLayout *rightColOpt = new QGridLayout();
	rightCol->addLayout(rightColOpt, 0, 0);

	label = new QLabel(trUtf8("Автоматическое повторное включение"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	rightColOpt->addWidget(label, row, 0);
	oCheckAutoSwitch = new QCheckBox();
	oCheckAutoSwitch->setLayoutDirection(Qt::RightToLeft);
	rightColOpt->addWidget(oCheckAutoSwitch, row++, 1);

	label = new QLabel(trUtf8("Выбор функции силового выхода"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	rightColOpt->addWidget(label, row, 0);
	oComboPowerOut = new QComboBox();
	oComboPowerOut->addItem(trUtf8("Стандартный"));
	oComboPowerOut->addItem(trUtf8("Звезда"));
	oComboPowerOut->addItem(trUtf8("Вращение вперёд"));
	rightColOpt->addWidget(oComboPowerOut, row++, 1);

	label = new QLabel(trUtf8("Выбор функции дополнительного выхода"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	rightColOpt->addWidget(label, row, 0);
	oComboAppendOut = new QComboBox();
	oComboAppendOut->addItem(trUtf8("Нет"));
	oComboAppendOut->addItem(trUtf8("Сигнализация аварии"));
	oComboAppendOut->addItem(trUtf8("Предупреждение о пуске"));
	oComboAppendOut->addItem(trUtf8("Предаварийная сигнализация"));
	oComboAppendOut->addItem(trUtf8("Дистанционно упр. выход"));
	oComboAppendOut->addItem(trUtf8("Треугольник"));
	oComboAppendOut->addItem(trUtf8("Вращение назад"));
	oComboAppendOut->addItem(trUtf8("Управление расцепителем"));
	rightColOpt->addWidget(oComboAppendOut, row++, 1);

	label = new QLabel(trUtf8("Задержка переключения"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	rightColOpt->addWidget(label, row, 0);
	oSpinDelaySwitch = new QSpinBox();
	oSpinDelaySwitch->setSuffix(trUtf8(" сек"));
	oSpinDelaySwitch->setRange(1, 30);
	rightColOpt->addWidget(oSpinDelaySwitch, row++, 1);

	label = new QLabel(trUtf8("Задержка включения"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	rightColOpt->addWidget(label, row, 0);
	oSpinDelaySwitchOn = new QSpinBox();
	oSpinDelaySwitchOn->setSuffix(trUtf8(" сек"));
	oSpinDelaySwitchOn->setRange(1, 255);
	rightColOpt->addWidget(oSpinDelaySwitchOn, row++, 1);

	label = new QLabel(trUtf8("Разрешение циклической работы по таймеру"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	rightColOpt->addWidget(label, row, 0);
	oCheckWorkByTimer = new QCheckBox();
	oCheckWorkByTimer->setLayoutDirection(Qt::RightToLeft);
	rightColOpt->addWidget(oCheckWorkByTimer, row++, 1);

	label = new QLabel(trUtf8("Продолжительность работы в циклическом режиме"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	rightColOpt->addWidget(label, row, 0);
	oSpinDelayWork = new QSpinBox();
	oSpinDelayWork->setSuffix(trUtf8(" мин"));
	oSpinDelayWork->setRange(1, 5940);
	rightColOpt->addWidget(oSpinDelayWork, row++, 1);

	label = new QLabel(trUtf8("Продолжительность простоя в циклическом режиме"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	rightColOpt->addWidget(label, row, 0);
	oSpinDelayPause = new QSpinBox();
	oSpinDelayPause->setSuffix(trUtf8(" мин"));
	oSpinDelayPause->setRange(1, 5940);
	rightColOpt->addWidget(oSpinDelayPause, row++, 1);

	label = new QLabel(trUtf8("Выбор функции входа 1"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	rightColOpt->addWidget(label, row, 0);
	oComboIn1 = new QComboBox();
	oComboIn1->addItem(trUtf8("Нет"));
	oComboIn1->addItem(trUtf8("Внешняя авария 1"));
	oComboIn1->addItem(trUtf8("Пуск(Двухпроводное управление)"));
	oComboIn1->addItem(trUtf8("Пуск(Трёхпроводное управление)"));
	oComboIn1->addItem(trUtf8("Вращение вперёд"));
	rightColOpt->addWidget(oComboIn1, row++, 1);

	label = new QLabel(trUtf8("Выбор функции входа 2"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	rightColOpt->addWidget(label, row, 0);
	oComboIn2 = new QComboBox();
	oComboIn2->addItem(trUtf8("Нет"));
	oComboIn2->addItem(trUtf8("Внешняя авария 2"));
	oComboIn2->addItem(trUtf8("Пуск(Двухпроводное управление)"));
	oComboIn2->addItem(trUtf8("Стоп(Трёхпроводное управление)"));
	oComboIn2->addItem(trUtf8("Вращение назад"));
	oComboIn2->addItem(trUtf8("Датчик влажности"));
	rightColOpt->addWidget(oComboIn2, row++, 1);

	label = new QLabel(trUtf8("Разрешение дистанционного управления"));
	label->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
	rightColOpt->addWidget(label, row, 0);
	oCheckAllowRemoteControll = new QCheckBox();
	oCheckAllowRemoteControll->setLayoutDirection(Qt::RightToLeft);
	rightColOpt->addWidget(oCheckAllowRemoteControll, row++, 1);

	rightColOpt->addItem(new QSpacerItem(0, 0, QSizePolicy::Preferred, QSizePolicy::Expanding), row++, 0);

	l->addItem(new QSpacerItem(0, 0, QSizePolicy::Preferred, QSizePolicy::Expanding), 1, 0, 1, 2);

	// Кнопки
	QGridLayout *btns = new QGridLayout();
	l->addLayout(btns, 2, 0, 1, 2);

	oBtnReadConfig = new QPushButton(trUtf8("Считать настройки"));
	btns->addWidget(oBtnReadConfig, 0, 0, 1, 1);
	connect(oBtnReadConfig, SIGNAL(clicked()), this, SLOT(onBtnReadConfigClicked()));

	oBtnWriteConfig = new QPushButton(trUtf8("Записать настройки"));
	btns->addWidget(oBtnWriteConfig, 0, 1, 1, 1);
	connect(oBtnWriteConfig, SIGNAL(clicked()), this, SLOT(onBtnWriteConfigClicked()));

	oBtnSetupTime = new QPushButton(trUtf8("Установить время УЗД"));
	btns->addWidget(oBtnSetupTime, 1, 0, 1, 2);
	connect(oBtnSetupTime, SIGNAL(clicked()), this, SLOT(onBtnWriteTimeClicked()));

	oBtnResetCrashProtocol = new QPushButton(trUtf8("Сброс протокола аварий"));
	btns->addWidget(oBtnResetCrashProtocol, 0, 2);
	connect(oBtnResetCrashProtocol, SIGNAL(clicked()), this, SLOT(onBtnResetCrashProtocolClicked()));

	oBtnResetWorkProtocol = new QPushButton(trUtf8("Сброс протокола работы двигателя"));
	btns->addWidget(oBtnResetWorkProtocol, 0, 3);
	connect(oBtnResetWorkProtocol, SIGNAL(clicked()), this, SLOT(onBtnResetWorkProtocol()));

	QBoxLayout* boxLayout = new QBoxLayout(QBoxLayout::LeftToRight);
	btns->addLayout(boxLayout, 1, 2, 1, 2);

	oBtnResetWorkTime = new QPushButton(trUtf8("Сброс наработки"));
	boxLayout->addWidget(oBtnResetWorkTime);
	connect(oBtnResetWorkTime, SIGNAL(clicked()), this, SLOT(onBtnResetWorkTime()));

	// Цепляем конфиги к методу поиска конфликтов
	connect(oCheckAllowRemoteControll, SIGNAL(stateChanged(int)), this, SLOT(onSetupChanged()));
	connect(oCheckWorkByTimer, SIGNAL(stateChanged(int)), this, SLOT(onSetupChanged()));
	connect(oCheckAllowWetProtect, SIGNAL(stateChanged(int)), this, SLOT(onSetupChanged()));
	connect(oComboIn1, SIGNAL(currentIndexChanged(int)), this, SLOT(onSetupChanged()));
	connect(oComboIn2, SIGNAL(currentIndexChanged(int)), this, SLOT(onSetupChanged()));
	connect(oComboPowerOut, SIGNAL(currentIndexChanged(int)), this, SLOT(onSetupChanged()));
	connect(oComboAppendOut, SIGNAL(currentIndexChanged(int)), this, SLOT(onSetupChanged()));
	connect(oCheckAllowFastProtect, SIGNAL(stateChanged(int)), this, SLOT(onSetupChanged()));
}

TabSetup::~TabSetup()
{

}
//======================================================================================
void TabSetup::onDataEvent(const DataEvent *e)
{
	switch (e->type())
	{
	case DET_CONNECT:
	{
		const DeviceInfo *dev = oMainWindow->deviceInfo();
		oDSpinNominalCur->setDecimals((dev->curScale() > 1) ? 1 : 0);
		oDSpinNominalCur->setMinimum(double(dev->curMin()));
		oDSpinNominalCur->setMaximum(double(dev->curMax()));

		oSpinTimeProtectOfBiasCurrents->setEnabled(dev->version() >= 50);
		oDSpinProtectionThresholdOfIdle->setEnabled(dev->version() >= 70);
		oComboProtectionThresholdOfInsulation->setEnabled(dev->version() >= 70);
		oSpinTimeProtectOfBiasCurrents->setValue(255);
	}
		break;
	case DET_CONFIG:
		updateData(static_cast<const ConfigEvent*>(e)->config());
	case DET_TIME_WRITED:
	case DET_TIME_FAIL:
	case DET_RESET_CRASH_PROTOCOL:
	case DET_RESET_CRASH_PROTOCOL_FAIL:
	case DET_RESET_WORK_PROTOCOL:
	case DET_RESET_WORK_PROTOCOL_FAIL:
	case DET_RESET_WORK_TIME:
	case DET_RESET_WORK_TIME_FAIL:
		oBtnReadConfig->setEnabled(true);
		oBtnWriteConfig->setEnabled(true);
		oBtnSetupTime->setEnabled(true);
		oBtnResetCrashProtocol->setEnabled(true);
		oBtnResetWorkProtocol->setEnabled(true);
		oBtnResetWorkTime->setEnabled(true);
		break;
	case DET_GET_DATA:
		oTime = static_cast<const DataEventGet*>(e)->data()->time();
		break;
	case DET_CHANGE_AUTO_CONFIG_STATE:
		if (static_cast<const ChangeAutoConfigState*>(e)->newState() ==
			RunConfigProgressPacket::S_COMPLETE)
			onBtnReadConfigClicked();
		break;
	default: break;
	}
}
//======================================================================================
void TabSetup::updateData(const ConfigPacket *config)
{
	oDSpinNominalCur->setValue(double(config->curNom() / oMainWindow->deviceInfo()->curScale()));
	oSpinAllowCur->setValue(config->curMin());
	oSpinOverloadCur->setValue(config->curOverload());
	oSpinOverloadTime->setValue(config->protectTime() / 10);
	oSpinImbalance->setValue(config->swOffPhaseImbalance());
	oSpinDelaySwitchOn->setValue(config->delayStart());
	oSpinAllowCrashPhase->setValue(config->countCrashPhases());
	oSpinTimeOff->setValue(config->offTimeDoubleOverload());
	oSpinTresholdTemp100->setValue(config->rt100temp());
	oCheckAllowFastProtect->setChecked(config->fastProtect());
	oCheckAutoSwitch->setChecked(config->autoStart());
	oCheckAllowTempProtect->setChecked(config->rtsProtect());
	oCheckAllowWetProtect->setChecked(config->wetnessProtect());

	oComboAllowVoltage->setCurrentIndex(config->volPhaseMode());
	oSpinDelayWork->setValue(config->workTimer());
	oSpinDelayPause->setValue(config->delayTimer());
	oComboIn1->setCurrentIndex(config->input1F());
	oComboIn2->setCurrentIndex(config->input2F());
	oComboPowerOut->setCurrentIndex(config->powerOutputF());
	oComboAppendOut->setCurrentIndex(config->appendOutputF());
	oSpinDelaySwitch->setValue(config->switchDelay());
	oCheckAllowRemoteControll->setChecked(config->remoteControl());
	oCheckTestingPhase->setChecked(config->testPhases());
	oCheckAllowTempProtect100->setChecked(config->rt100Protect());
	oCheckWorkByTimer->setChecked(config->cicleTimer());

	if (gDeviceVersion >= 50)
	{
		oSpinTimeProtectOfBiasCurrents->setValue(static_cast<const ConfigPacketV50*>(config)->timeProtectOfBiasCurrents() / 10);
	}
	if (gDeviceVersion >= 70)
	{
		const ConfigPacketV70 *config70 = static_cast<const ConfigPacketV70*>(config);
		oDSpinProtectionThresholdOfIdle->setValue(double(config70->protectionThresholdOfIdle()));

		oComboProtectionThresholdOfInsulation->setCurrentIndex(config70->protectionThresholdOfInsulation());
	}
}
//======================================================================================
void TabSetup::disableButtons()
{
	oBtnReadConfig->setEnabled(false);
	oBtnWriteConfig->setEnabled(false);
	oBtnSetupTime->setEnabled(false);
	oBtnResetCrashProtocol->setEnabled(false);
	oBtnResetWorkProtocol->setEnabled(false);
	oBtnResetWorkTime->setEnabled(false);
}
//======================================================================================
void TabSetup::onBtnReadConfigClicked()
{
	oMainWindow->readConfig();
	disableButtons();
}

void TabSetup::onBtnWriteConfigClicked()
{
	ConfigPacket *config;

	if (gDeviceVersion >= 70)
		config = new ConfigPacketV70();
	else if (gDeviceVersion >= 50)
		config = new ConfigPacketV50();
	else
		config = new ConfigPacket();

	if (gDeviceVersion >= 70)
	{
		ConfigPacketV70 *config70 = static_cast<ConfigPacketV70*>(config);
		config70->setProtectionThresholdOfIdle(float(oDSpinProtectionThresholdOfIdle->value()));
		config70->setProtectionThresholdOfInsulation(oComboProtectionThresholdOfInsulation->currentIndex());
	}
	if (gDeviceVersion >= 50)
	{
		static_cast<ConfigPacketV50*>(config)->setTimeProtectOfBiasCurrents(uint(oSpinTimeProtectOfBiasCurrents->value() * 10));
	}

	config->setCurNom(float(oDSpinNominalCur->value() * oMainWindow->deviceInfo()->curScale()));
	config->setCurMin(oSpinAllowCur->value());
	config->setCurOverload(oSpinOverloadCur->value());
	config->setProtectTime(oSpinOverloadTime->value() * 10);
	config->setSwOffPhaseImbalance(oSpinImbalance->value());
	config->setDelayStart(oSpinDelaySwitchOn->value());
	config->setCountCrashPhases(oSpinAllowCrashPhase->value());
	config->setOffTimeDoubleOverload(oSpinTimeOff->value());
	config->setRT100Temp(oSpinTresholdTemp100->value());
	config->setFastProtect(oCheckAllowFastProtect->isChecked());
	config->setAutoStart(oCheckAutoSwitch->isChecked());
	config->setRTSProtect(oCheckAllowTempProtect->isChecked());
	config->setWetnessProtect(oCheckAllowWetProtect->isChecked());

	config->setVolPhaseMode(oComboAllowVoltage->currentIndex());
	config->setWorkTimer(oSpinDelayWork->value());
	config->setDelayTimer(oSpinDelayPause->value());
	config->setInput1F(oComboIn1->currentIndex());
	config->setInput2F(oComboIn2->currentIndex());
	config->setPowerOutputF(oComboPowerOut->currentIndex());
	config->setAppendOutputF(oComboAppendOut->currentIndex());
	config->setSwitchDelay(oSpinDelaySwitch->value());
	config->setRemoteControl(oCheckAllowRemoteControll->isChecked());
	config->setTestPhases(oCheckTestingPhase->isChecked());
	config->setRT100Protect(oCheckAllowTempProtect100->isChecked());
	config->setCicleTimer(oCheckWorkByTimer->isChecked());

	oMainWindow->writeConfig(config);

	disableButtons();
}
//======================================================================================
void TabSetup::onBtnWriteTimeClicked()
{
	if (!oMainWindow->hasPassword())
	{
		QMessageBox::warning(this, trUtf8("Настройка"),
						trUtf8("Для этой операции необходимо ввести пароль."),
						QMessageBox::Ok, QMessageBox::Ok);
		oMainWindow->focusEditPassword();
		return;
	}

	TimeDialog timeDialog(oTime);
	if (timeDialog.exec() == QDialog::Accepted)
	{
		oMainWindow->writeTime(timeDialog.time());

		disableButtons();
	}
}

void TabSetup::onBtnResetCrashProtocolClicked()
{
	if (!oMainWindow->hasPassword())
	{
		QMessageBox::warning(this, trUtf8("Настройка"),
						trUtf8("Для этой операции необходимо ввести пароль."),
						QMessageBox::Ok, QMessageBox::Ok);
		oMainWindow->focusEditPassword();
		return;
	}

	oMainWindow->resetCrashProtocol();
	disableButtons();
}

void TabSetup::onBtnResetWorkProtocol()
{
	if (!oMainWindow->hasPassword())
	{
		QMessageBox::warning(this, trUtf8("Настройка"),
						trUtf8("Для этой операции необходимо ввести пароль."),
						QMessageBox::Ok, QMessageBox::Ok);
		oMainWindow->focusEditPassword();
		return;
	}

	oMainWindow->resetWorkProtocol();
	disableButtons();
}

void TabSetup::onBtnResetWorkTime()
{
	if (!oMainWindow->hasPassword())
	{
		QMessageBox::warning(this, trUtf8("Настройка"),
						trUtf8("Для этой операции необходимо ввести пароль."),
						QMessageBox::Ok, QMessageBox::Ok);
		oMainWindow->focusEditPassword();
		return;
	}

	oMainWindow->resetWorkTime();
	disableButtons();
}
//======================================================================================
void TabSetup::onBtnShowIdlePlot()
{
	IdlePlotDialog *dialog = new IdlePlotDialog(oDSpinNominalCur->value(), oSpinAllowCur->value() * 0.01,
			oComboAllowVoltage->currentIndex(), oDSpinProtectionThresholdOfIdle->value());

	dialog->exec();

	delete dialog;
}
//======================================================================================
void TabSetup::onSetupChanged()
{
	static const QString conflictStyle("background-color: #FF3300;");
	static const QString comboConflictStyle(":editable { background-color: #FF3300; } ");

	oComboIn1->setStyleSheet(QString());
	oComboIn2->setStyleSheet(QString());
	oCheckAllowRemoteControll->setStyleSheet(QString());
	oCheckWorkByTimer->setStyleSheet(QString());
	oComboPowerOut->setStyleSheet(QString());
	oComboAppendOut->setStyleSheet(QString());
	oCheckAllowWetProtect->setStyleSheet(QString());
	oCheckAllowFastProtect->setStyleSheet(QString());

	bool hasConflicts = false;

	// oComboIn1
	if (oComboIn1->currentIndex() == 2)
	{
		bool isConflict = false;
		if (oComboIn2->currentIndex() == 2)
		{
			isConflict = true;
			oComboIn2->setStyleSheet(comboConflictStyle);
		}
		if (oCheckAllowRemoteControll->isChecked())
		{
			isConflict = true;
			oCheckAllowRemoteControll->setStyleSheet(conflictStyle);
		}

		if (isConflict)
		{
			oComboIn1->setStyleSheet(comboConflictStyle);
			hasConflicts = true;
		}
	}
	// oComboIn2
	if (oComboIn2->currentIndex() == 2)
	{
		bool isConflict = false;
		if (oComboIn1->currentIndex() == 2 || oComboIn1->currentIndex() == 3 ||
				oComboIn1->currentIndex() == 4)
		{
			isConflict = true;
			oComboIn1->setStyleSheet(comboConflictStyle);
		}
		if (oCheckAllowRemoteControll->isChecked())
		{
			isConflict = true;
			oCheckAllowRemoteControll->setStyleSheet(conflictStyle);
		}

		if (isConflict)
		{
			oComboIn2->setStyleSheet(comboConflictStyle);
			hasConflicts = true;
		}
	}
	// oComboIn2
	if (oComboIn2->currentIndex() == 3)
	{
		bool isConflict = false;
		if (oComboIn1->currentIndex() != 3)
		{
			isConflict = true;
			oComboIn1->setStyleSheet(comboConflictStyle);
		}
		if (oCheckAllowRemoteControll->isChecked())
		{
			isConflict = true;
			oCheckAllowRemoteControll->setStyleSheet(conflictStyle);
		}

		if (isConflict)
		{
			oComboIn2->setStyleSheet(comboConflictStyle);
			hasConflicts = true;
		}
	}
	// oComboIn2
	if (oComboIn2->currentIndex() == 4)
	{
		bool isConflict = false;

		if (oComboIn1->currentIndex() != 4)
		{
			isConflict = true;
			oComboIn1->setStyleSheet(comboConflictStyle);
		}
		if (oCheckAllowRemoteControll->isChecked())
		{
			isConflict = true;
			oCheckAllowRemoteControll->setStyleSheet(conflictStyle);
		}

		if (isConflict)
		{
			oComboIn2->setStyleSheet(comboConflictStyle);
			hasConflicts = true;
		}
	}
	// oComboIn2
	if (oComboIn2->currentIndex() == 4)
	{
		bool isConflict = false;

		if (oComboIn1->currentIndex() != 4)
		{
			isConflict = true;
			oComboIn1->setStyleSheet(comboConflictStyle);
		}
		if (oCheckAllowRemoteControll->isChecked())
		{
			isConflict = true;
			oCheckAllowRemoteControll->setStyleSheet(conflictStyle);
		}

		if (isConflict)
		{
			oComboIn2->setStyleSheet(comboConflictStyle);
			hasConflicts = true;
		}
	}
	// oComboIn2
	if (oComboIn2->currentIndex() == 5 ||
			oCheckAllowWetProtect->isChecked())
	{
		if (oComboIn2->currentIndex() != 5 ||
			!oCheckAllowWetProtect->isChecked())
		{
			oComboIn2->setStyleSheet(comboConflictStyle);
			oCheckAllowWetProtect->setStyleSheet(conflictStyle);
			hasConflicts = true;
		}
	}

	// oCheckAllowRemoteControll
	if (oCheckAllowRemoteControll->isChecked())
	{
		bool isConflict = false;
		if (oCheckWorkByTimer->isChecked())
		{
			oCheckWorkByTimer->setStyleSheet(conflictStyle);
			isConflict = true;
		}

		if (isConflict)
		{
			oCheckAllowRemoteControll->setStyleSheet(conflictStyle);
			hasConflicts = true;
		}
	}
	// oComboPowerOut
	if (oComboPowerOut->currentIndex() == 1 ||
			oComboAppendOut->currentIndex() == 5)
	{
		if (oComboPowerOut->currentIndex() != 1 ||
				oComboAppendOut->currentIndex() != 5)
		{
			oComboPowerOut->setStyleSheet(comboConflictStyle);
			oComboAppendOut->setStyleSheet(comboConflictStyle);
			hasConflicts = true;
		}
	}
	// oComboPowerOut
	if (oComboPowerOut->currentIndex() == 2 ||
			oComboAppendOut->currentIndex() == 6)
	{
		if (oComboPowerOut->currentIndex() != 2 ||
				oComboAppendOut->currentIndex() != 6)
		{
			oComboPowerOut->setStyleSheet(comboConflictStyle);
			oComboAppendOut->setStyleSheet(comboConflictStyle);
			hasConflicts = true;
		}
	}

	if (oCheckAllowFastProtect->isChecked() ||
			oComboAppendOut->currentIndex() == 7)
	{
		if (!oCheckAllowFastProtect->isChecked()||
				oComboAppendOut->currentIndex() != 7)
		{
			oCheckAllowFastProtect->setStyleSheet(conflictStyle);
			oComboAppendOut->setStyleSheet(comboConflictStyle);
			hasConflicts = true;
		}
	}

	oBtnWriteConfig->setEnabled(!hasConflicts);
}
//======================================================================================
